<%@ page language="java" contentType="text/html; charset=UTF-8"
		 pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page import="cn.estore.entity.Product" %>
<%@ page import="cn.estore.dao.ProductDao" %>
<%@ page import="cn.estore.entity.Order" %>
<%@ page import="cn.estore.dao.OrderDao" %>
<%@ page import="java.sql.SQLException" %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>商品折扣信息展示</title>
	<style>
		body {
			font-family: Arial, sans-serif;
			background-color: #f8f9fa;
			margin: 0;
			padding: 0;
			text-align: center;
		}

		header {
			background-color: #343a40;
			color: white;
			padding: 20px 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-left: 20px;
			padding-right: 20px;
		}

		header a {
			color: white;
			text-decoration: none;
			margin: 0 15px;
		}

		header span {
			color: white;
			font-weight: bold;
		}

		main {
			padding: 20px;
		}

		table {
			width: 80%;
			margin: 20px auto;
			border-collapse: collapse;
			box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
		}

		th, td {
			padding: 15px;
			text-align: left;
			border-bottom: 1px solid #ddd;
		}

		img {
			max-width: 100%;
			max-height: 150px;
			display: block;
			margin: 0 auto;
		}

		.product-info {
			padding-left: 20px;
		}

		/* 新增的用于隐藏元素的CSS类 */
		.hide {
			display: none;
		}

		/* 退出按钮样式 */
		.logout-btn {
			color: white;
			text-decoration: none;
			background-color: #dc3545;
			padding: 8px 15px;
			border-radius: 4px;
		}

		.logout-btn:hover {
			background-color: #c82333;
		}

		/* 立即购买按钮样式 */
		.buy-btn {
			color: white;
			text-decoration: none;
			background-color: #007bff;
			padding: 8px 15px;
			border-radius: 4px;
			cursor: pointer;
		}

		.buy-btn:hover {
			background-color: #0056b3;
		}

		input[type="number"] {
			width: 60px;
			padding: 5px;
			border: 1px solid #ccc;
			border-radius: 4px;
		}

		/* 订单查询按钮样式 */
		.query-order-btn {
			color: white;
			text-decoration: none;
			background-color: #28a745;
			padding: 8px 15px;
			border-radius: 4px;
			margin-top: 20px;
			cursor: pointer;
		}

		.query-order-btn:hover {
			background-color: #218838;
		}
	</style>
</head>
<body>
<header>
	<%
		// 检查用户是否登录，这里通过查找名为"username"的Cookie来简单判断（可根据实际登录逻辑完善）
		boolean isLoggedIn = false;
		String username = "";
		Cookie[] cookies = request.getCookies();
		if (cookies!= null) {
			for (Cookie cookie : cookies) {
				if ("username".equals(cookie.getName())) {
					isLoggedIn = true;
					username = cookie.getValue();
					break;
				}
			}
		}

		if (isLoggedIn) {
			// 如果登录，为登录按钮添加hide类，使其隐藏，并显示退出按钮
			out.println("<a href='login.jsp' class='hide'>登录</a>");
			out.println("<a href='javascript:void(0);' class='logout-btn' onclick='logout();'>退出</a>");
	%>
	<span id="loggedInUser">欢迎您，<%=username%></span>
	<%
		} else {
			// 如果未登录，正常输出登录按钮的HTML代码，不显示退出按钮
			out.println("<a href='login.jsp'>登录</a>");
			out.println("<a href='javascript:void(0);' class='hide logout-btn'>退出</a>");
		}
	%>
	<a href="zhuce.jsp">注册</a>
</header>
<main>
	<%
		if (isLoggedIn) {
			ProductDao productDao = new ProductDao();
			List<Product> ProductList = productDao.selectDiscountProducts();
			for (int i = 0; i < ProductList.size(); i++) {
				Product e = ProductList.get(i);
	%>
	<table border="1" align="center">
		<tr>
			<td width="40%">
				<img src="<%="productImages/" + e.getPicture()%>" alt="商品图片">
			</td>
			<td class="product-info">
				<form action="<%=request.getContextPath()%>/buyProduct.jsp" method="get">
					<div>商品：<%=e.getName()%></div>
					<div>价格：<%=e.getMarketPrice()%>元</div>
					<div>简介：<%=e.getDescription()%></div>
					<input type="hidden" name="productId" value="<%=e.getId()%>">
					<div>
						购买数量：<input type="number" min="1" name="quantity" value="1">
					</div>
					<input type="submit" value="立即购买" class="buy-btn" onclick="return confirm('确定要购买该商品吗？');">
				</form>
				<%-- 如果登录，添加hide类隐藏“登录才能购买”提示信息 --%>
				<% if (isLoggedIn) { %>
				<div class="hide">登录才能购买</div>
				<% } else { %>
				<div>登录才能购买</div>
				<% } %>
			</td>
		</tr>
	</table>
	<%
		}
	%>
	<a href="<%=request.getContextPath()%>/queryOrder.jsp" class="query-order-btn">查询订单</a>
	<%
		} else {
			out.println("<p>您还未登录，请先登录后查看商品信息。</p><a href='login.jsp'>点击登录</a>");
		}
	%>
</main>
<script>
	function logout() {
		// 创建一个名为username的Cookie，设置其过期时间为过去的时间，实现清除Cookie的效果
		document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
		// 跳转到登录页面
		window.location.href = "login.jsp";
	}
</script>
<%
	if ("GET".equals(request.getMethod())) {
		// 获取购买数量和商品ID，并添加非空判断
		String quantityStr = request.getParameter("quantity");
		String productIdStr = request.getParameter("productId");
		System.out.println("quantityStr: " + quantityStr);
		System.out.println("productIdStr: " + productIdStr);
		if (quantityStr!= null && productIdStr!= null) {
			int quantity = Integer.parseInt(quantityStr);
			int productId = Integer.parseInt(productIdStr);

			// 获取当前用户的ID，这里假设通过查找名为"user_id"的Cookie来获取（实际需根据登录逻辑准确获取）
			int userId = 0;
			Cookie[] userCookies = request.getCookies();
			if (userCookies!= null) {
				for (Cookie cookie : userCookies) {
					if ("user_id".equals(cookie.getName())) {
						userId = Integer.parseInt(cookie.getValue());
						break;
					}
				}
			}

			// 获取商品信息用于计算价格等（这里简化处理，实际可能需更多校验和逻辑）
			ProductDao productDao = new ProductDao();
			Product product = null;
			product = productDao.selectProductById(productId);

			if (product!= null) {
				double actualPrice = product.getMarketPrice(); // 这里假设实际价格就是市场价格，可根据实际优惠等调整
				double totalAmount = actualPrice * quantity;

				Order order = new Order();
				order.setUserId(userId);
				order.setProductId(productId);
				order.setProductQuantity(quantity);
				order.setActualPrice(actualPrice);
				order.setTotalAmount(totalAmount);
				// 生成订单编号，这里简单示例，实际需按更合理规则生成
				String orderNumber = "ORDER_" + System.currentTimeMillis();
				order.setOrderNumber(orderNumber);

				OrderDao orderDao = new OrderDao();
				boolean insertSuccess = false;
				insertSuccess = orderDao.insertOrder(order);

				if (insertSuccess) {
					out.println("<p>订单插入成功，感谢您的购买！您的订单编号为：" + orderNumber + "</p>");
				} else {
					out.println("<p>订单插入失败，请检查信息后重试。</p>");
				}
			} else {
				out.println("<p>商品不存在，请检查商品ID是否正确。</p>");
			}
		}
	}
%>
</body>
</html>
